package com.fangcun.filter.logs;

import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.fangcun.bean.sys.ResponseMsg;
import com.fangcun.common.auth.UserAuthMethod;
import com.fangcun.common.util.PublicMethod;
import com.fangcun.common.util.json.JSONTools;
import com.fangcun.entity.LogsRequestAll;
import com.fangcun.service.SystemService;

public class HttpServletLogFilter implements Filter {

	@Resource(name = "systemService")
	private SystemService systemService;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		LogsRequestAll logs = new LogsRequestAll();
		String ip = PublicMethod.getIp(req);
		String url = req.getRequestURI();
		String method = req.getMethod();
		String sessionId = PublicMethod.getUUIDUpperCase();
		String userKey = req.getHeader("appkey");
		try {
			logs.setRequestIp(ip);
			logs.setSessionId(sessionId);
			request.setAttribute(ResponseMsg.SESSIONID, sessionId);
			logs.setUserkey(userKey);
			logs.setRequestUrl(url);
			logs.setRequestMethod(method);
			logs.setRequestTime(new Date());
			try {
				logs.setUserId(UserAuthMethod.getLoginRedisKeyClass(req.getHeader(UserAuthMethod.LOGIN_TOKEN_NAME)).getUserId());
			} catch (Exception e) {
				logs.setUserId(0L);
			}
			Enumeration<String> headParam = req.getHeaderNames();
			Map<String, String> map = new HashMap<String, String>();
			while (headParam.hasMoreElements()) {
				String paramName = headParam.nextElement();
				String value = req.getHeader(paramName);
				map.put(paramName, value);
			}
			logs.setRequestHeadParam(JSONTools.obj2json(map));
			Enumeration<String> params = request.getParameterNames();
			map = new HashMap<String, String>();
			while (params.hasMoreElements()) {
				String paramName = params.nextElement();
				String value = request.getParameter(paramName);
				map.put(paramName, value);
			}
			logs.setRequestFormParam(JSONTools.obj2json(map));

			// 请求值获取
			ServletRequest requestWrapper = null;
			ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) response);
			if (request instanceof HttpServletRequest) {
				requestWrapper = new RequestWrapper((HttpServletRequest) request);
				RequestWrapper myRequestWrapper = (RequestWrapper) requestWrapper;
				String body = myRequestWrapper.getBody();
				if (!StringUtils.isEmpty(body)) {
					try {
						logs.setRequestIoParam(JSONTools.obj2json(JSONTools.convertJsonStrToMap(body)));
					} catch (Exception e) {
						logs.setRequestIoParam(body);
					}
				}
			}

			chain.doFilter(requestWrapper, responseWrapper);

			// 获取返回值
			byte[] content = responseWrapper.getContent();
			// 判断是否有值
			if (content.length > 0) {
				String str = new String(content, "UTF-8");
				ServletOutputStream out = response.getOutputStream();
				out.write(content);
				out.flush();

				try {
					logs.setResponseParam(str.trim());
					logs.setResponseTime(new Date());
					logs.setUseTime((int) (logs.getResponseTime().getTime() - logs.getRequestTime().getTime()));
					if (!url.contains("/admin/botany/v1.0/message/image/read") && !url.contains("/admin/botany/v1.0/message/down")) {
						systemService.insertLogs(logs);
					}
				} catch (Exception e) {
				}
			}
		} catch (Exception e) {
			chain.doFilter(request, response);
		}
	}

	@Override
	public void destroy() {

	}
}